package com.yeyks.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author fuchangshuai
 * @date 2019/4/3 5:25 PM
 */
@Component
@ServerEndpoint(value = "/webSocket/{userId}")
@Slf4j
public class WebSocket {
    /**
     * 用户id
     */
    private Integer userId;
    /**
     * 格式:Map<用户id, Map<session id, session对象>>
     */
    private static Map<Integer, Map<String, Session>> clientMap = new ConcurrentHashMap<>();

    /**
     * 添加用户
     *
     * @param userId
     * @param session
     */
    public static void add(Integer userId, Session session) {
        synchronized (WebSocket.class + ":" + userId) {
            Map<String, Session> stringSessionMap = clientMap.get(userId);
            if (null == stringSessionMap) {
                stringSessionMap = new ConcurrentHashMap<>();
                clientMap.put(userId, stringSessionMap);
            }
            stringSessionMap.put(session.getId(), session);
        }
    }

    /**
     * 移除用户
     *
     * @param userId
     */
    static void remove(Integer userId, String sessionId) {
        try {
            clientMap.get(userId).remove(sessionId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建立连接
     */
    @OnOpen
    public void onOpen(@PathParam("userId") Integer userId, Session session) {
        try {
            if (null != userId) {
//                log.info("现在连接的客户id：" + session.getId() + "，用户id为：" + userId);
                this.userId = userId;
                add(userId, session);
            }
        } catch (Exception e) {
            log.info("错误信息{}", e.getLocalizedMessage());
            remove(userId, session.getId());
        }

    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("websocket和服务端连接断开" + error.getMessage());
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(Session session) {
        log.info("现在连接的客户id：" + session.getId() + "，用户id为：" + userId);
        remove(userId, session.getId());
    }

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
//            log.info("收到客户端的消息message = {}", message);
            session.getAsyncRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给指定用户推消息
     *
     * @param toUserId
     * @param message
     */
    public void sendMessageToUser(Integer toUserId, String message) {
        Map<String, Session> stringSessionMap = clientMap.get(toUserId);
        if (null != stringSessionMap) {
            for (Session session : stringSessionMap.values()) {
                session.getAsyncRemote().sendText(message);
            }
        } else {
            log.info("websocket该用户未连接userId = {}", toUserId);
        }
    }
}
